<?php
declare (strict_types=1);

namespace app\admin\controller\tally;

use app\admin\controller\CommonController;
use app\common\model\AclUser;
use app\common\model\TallyCollect;
use app\common\model\TallyCollectRatio;
use app\common\model\TallyCustom;
use think\db\BaseQuery;

class Ratio extends CommonController
{
    protected $modelName = TallyCollectRatio::MODEL_NAME;
    protected $alias = 'r';
    protected $createByField = false;
    protected $updateByField = false;

    protected function buildWhere(array $param): array
    {
        if (!empty($param['coll_collect_month_ge'])) {
            $param['coll_collect_month_ge'] = $param['coll_collect_month_ge'] . '-01';
        }
        if (!empty($param['coll_collect_month_le'])) {
            $param['coll_collect_month_le'] = $param['coll_collect_month_le'] . '-01';
        }
        return parent::buildWhere($param);
    }

    protected function indexPage($param)
    {
        if (empty($param['r_assigner_id_eq'])) {
            $param['r_assigner_id_eq'] = 0;
        }
        if (empty($param['coll_custom_id_eq'])) {
            $param['coll_custom_id_eq'] = 0;
        }
        trace($param);
        return parent::indexPage($param);
    }

    protected function getBaseModel(): BaseQuery
    {
        return parent::getBaseModel()
            ->leftJoin(TallyCollect::MODEL_NAME . ' coll', "coll.id={$this->alias}.collect_id")
            ->leftJoin(TallyCustom::MODEL_NAME . ' c', "c.id=coll.custom_id")
            ->leftJoin(AclUser::MODEL_NAME . ' u', "u.id={$this->alias}.assigner_id");
    }

    protected function getSearchFields(): string
    {
        return "{$this->alias}.*,DATE_FORMAT(coll.collect_month,'%Y-%m') _month"
            . ",concat(u.username,u.nickname) assigner_name,c.number,c.name custom_name"
            . ",round(coll.money*r.ratio/100,2) total_money";
    }

    protected function setDefaultValueInAddPage(array $row): array
    {
        $row['collect_id'] = request()->param('collect_id');
        $row['assigner_id'] = 0;
        return parent::setDefaultValueInAddPage($row);
    }
}
